<template>
  <div class="user-photo">
    <img :src="img" ref="img" alt="" class="img" />
    <div class="btn">
      <div @click="$emit('close')">取消</div>
      <div @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  name: 'UserPhotoPopup',
  data() {
    return {
      cropper: null
    }
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  methods: {
    onConfirm() {
      // 基于服务端的裁剪  getData()方法，该方法得到裁剪区域的区域参数
      // console.log(this.cropper.getData())
      // 纯客户端的图片裁剪,使用getCroppedCanvas()方法,该方法得到裁剪之后的图片对象,
      // 类似于URL.createObjectURL方法
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.upDataPhoto(blob)
      })
    },
    async upDataPhoto(blob) {
      this.$toast.loading({
        message: '修改中...', // 提示词
        forbidClick: true,
        duration: 0 // 持续时间 当前一直持续
      })

      try {
        /**
         * 如果接口要求Content-Type 是 application/json，则传递普通js对象
         * updateUserPhoto({
         *  photo:blob
         * })
         *
         * 如果接口要求Content-Type 是 multipart/form-data
         * 则必须传递FormData对象
         */
        const formData = new FormData()

        formData.append('photo', blob)

        const { data } = await updateUserPhoto(formData) // 请求数据接口

        this.$emit('close') // 关闭弹出层
        this.$emit('upData-photo', data.data.photo) // 更新父组件头像数据
        this.$toast.success('修改成功')
      } catch (error) {
        console.log(error)
        this.$toast.fail('修改头像失败')
      }
    }
  },
  mounted() {
    // cropper 图片裁剪器 网址：https://github.com/fengyuanchen/cropperjs

    const image = this.$refs.img // 获取imgDOM元素
    this.cropper = new Cropper(image, {
      // cropper 配置信息
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  }
}
</script>

<style lang="less" scoped>
.user-photo {
  background-color: #000;
  height: 100%;
  .img {
    max-width: 100%;
    display: block;
  }
  .btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    div {
      height: 90px;
      width: 90px;
      font-size: 30px;
      text-align: center;
      line-height: 90px;
      color: #fff;
    }
  }
}
</style>
